<template>
  <div class="supplier-list-page">
    <el-card class="filter-card">
      <el-form :inline="true" :model="searchForm" label-width="100">
        <el-form-item label="供应商名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入供应商名称"
            clearable
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="供应商等级">
          <el-select
            v-model="searchForm.grade"
            placeholder="请选择供应商等级"
            clearable
            filterable
            style="width: 220px"
            :loading="gradeOptionsLoading"
          >
            <el-option
              v-for="item in gradeOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <div class="table-toolbar">
        <el-button type="success" @click="openCreateDialog">新增供应商</el-button>
        <el-button
          type="danger"
          :disabled="!selectedIds.length"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="suppnumber" label="供应商编号" min-width="140" />
        <el-table-column prop="suppname" label="供应商名称" min-width="160" />
        <el-table-column prop="suppgrade" label="供应商等级" min-width="140" />
        <el-table-column prop="supppeople" label="联系人" min-width="120" />
        <el-table-column prop="phone" label="联系电话" min-width="140" />
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="desc"
          label="备注"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="openEditDialog(row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.totalCount"
          v-model:current-page="pagination.pageindex"
          v-model:page-size="pagination.pagesize"
          :page-sizes="[10, 20, 30, 50]"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <el-dialog
      draggable
      v-model="dialogVisible"
      :title="dialogTitle"
      width="520px"
      destroy-on-close
    >
      <el-form
        ref="dialogFormRef"
        :model="dialogForm"
        :rules="dialogRules"
        label-width="100"
      >
        <el-form-item label="供应商编号" prop="suppnumber">
          <el-input v-model="dialogForm.suppnumber" placeholder="请输入供应商编号" />
        </el-form-item>
        <el-form-item label="供应商名称" prop="suppname">
          <el-input v-model="dialogForm.suppname" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="供应商等级" prop="suppgrade">
          <el-select
            v-model="dialogForm.suppgrade"
            placeholder="请选择供应商等级"
            filterable
            allow-create
            default-first-option
            style="width: 100%"
            :loading="gradeOptionsLoading"
          >
            <el-option
              v-for="item in gradeOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="supppeople">
          <el-input v-model="dialogForm.supppeople" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="dialogForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="dialogForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="desc">
          <el-input
            v-model="dialogForm.desc"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="saving" @click="handleSubmit">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, computed } from 'vue'
import https from '@/Http/http'
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules
} from 'element-plus'

interface Supplier {
  id: number
  suppnumber: string
  suppname: string
  suppgrade: string
  supppeople: string
  phone: string
  status: number
  desc: string
}


const loading = ref(false)
const saving = ref(false)
const tableData = ref<Supplier[]>([])
const gradeOptions = ref<string[]>([])
const gradeOptionsLoading = ref(false)
const multipleSelection = ref<Supplier[]>([])

const pagination = reactive({
  pageindex: 1,
  pagesize: 10,
  totalCount: 0
})

const searchForm = reactive({
  name: '',
  grade: '',
  status: undefined as undefined | number
})

const statusOptions = [
  { label: '启用', value: 1 },
  { label: '禁用', value: 0 }
]

const dialogVisible = ref(false)
const dialogTitle = ref('新增供应商')
const dialogMode = ref<'create' | 'edit'>('create')
const dialogFormRef = ref<FormInstance>()
const dialogForm = reactive({
  id: 0,
  suppnumber: '',
  suppname: '',
  suppgrade: '',
  supppeople: '',
  phone: '',
  status: 1,
  desc: ''
})

const dialogRules: FormRules = {
  suppnumber: [{ required: true, message: '请输入供应商编号', trigger: 'blur' }],
  suppname: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
  suppgrade: [{ required: true, message: '请输入供应商等级', trigger: 'blur' }],
  supppeople: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const selectedIds = computed(() => multipleSelection.value.map(item => item.id))

const getStatusCode = (payload: any) => payload?.code ?? payload?.Code
const getPayloadData = <T = any>(payload: any): T =>
  (payload?.data ?? payload?.Data) as T
const getPayloadMsg = (payload: any): string =>
  payload?.msg ?? payload?.Msg ?? ''
const getTotalCount = (payload: any) =>
  payload?.totalCount ?? payload?.TotalCount ?? 0

const fetchSuppliers = async () => {
  loading.value = true
  try {
    const params = {
      pageindex: pagination.pageindex,
      pagesize: pagination.pagesize,
      name: searchForm.name || undefined,
      grade: searchForm.grade || undefined,
      status: searchForm.status !== undefined ? searchForm.status : undefined
    }
    const { data } = await https.Reads.get("/Supplier/ShowSupplier", { params })
    if (getStatusCode(data) === 1) {
      tableData.value = getPayloadData<Supplier[]>(data) ?? []
      pagination.totalCount = getTotalCount(data)
    } else {
      ElMessage.error(getPayloadMsg(data) || '获取供应商失败')
    }
  } catch (error: any) {
    console.error('fetchSuppliers error', error)
    ElMessage.error(error?.message || '获取供应商失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const fetchSupplierGrades = async () => {
  gradeOptionsLoading.value = true
  try {
    const { data } = await https.Reads.get("/Supplier/ShowSupplier", {
      params: { pageindex: 1, pagesize: 1000 }
    })
    if (getStatusCode(data) === 1) {
      const suppliers = getPayloadData<Supplier[]>(data) ?? []
      const uniqueGrades = Array.from(
        new Set(suppliers.map(item => item.suppgrade).filter(item => item && item.trim()))
      ).sort()
      gradeOptions.value = uniqueGrades
    }
  } catch (error: any) {
    console.error('fetchSupplierGrades error', error)
  } finally {
    gradeOptionsLoading.value = false
  }
}

const handleSearch = () => {
  pagination.pageindex = 1
  fetchSuppliers()
}

const handleReset = () => {
  searchForm.name = ''
  searchForm.grade = ''
  searchForm.status = undefined
  pagination.pageindex = 1
  fetchSuppliers()
}

const handleSizeChange = (val: number) => {
  pagination.pagesize = val
  pagination.pageindex = 1
  fetchSuppliers()
}

const handlePageChange = (val: number) => {
  pagination.pageindex = val
  fetchSuppliers()
}

const handleSelectionChange = (rows: Supplier[]) => {
  multipleSelection.value = rows
}

const resetDialogForm = () => {
  dialogForm.id = 0
  dialogForm.suppnumber = ''
  dialogForm.suppname = ''
  dialogForm.suppgrade = ''
  dialogForm.supppeople = ''
  dialogForm.phone = ''
  dialogForm.status = 1
  dialogForm.desc = ''
  dialogFormRef.value?.clearValidate()
}

const openCreateDialog = () => {
  dialogMode.value = 'create'
  dialogTitle.value = '新增供应商'
  resetDialogForm()
  dialogVisible.value = true
}

const openEditDialog = (row: Supplier) => {
  dialogMode.value = 'edit'
  dialogTitle.value = '编辑供应商'
  dialogForm.id = row.id
  dialogForm.suppnumber = row.suppnumber
  dialogForm.suppname = row.suppname
  dialogForm.suppgrade = row.suppgrade
  dialogForm.supppeople = row.supppeople || ''
  dialogForm.phone = row.phone
  dialogForm.status = row.status
  dialogForm.desc = row.desc || ''
  dialogVisible.value = true
  dialogFormRef.value?.clearValidate()
}

const submitAdd = async () => {
  const payload = {
    suppnumber: dialogForm.suppnumber,
    suppname: dialogForm.suppname,
    suppgrade: dialogForm.suppgrade,
    supppeople: dialogForm.supppeople,
    phone: dialogForm.phone,
    status: dialogForm.status,
    desc: dialogForm.desc
  }
  const { data } = await https.Writes.post("/Supplier/AddSupplier", payload)
  return data
}

const submitUpdate = async () => {
  const payload = {
    id: dialogForm.id,
    suppnumber: dialogForm.suppnumber,
    suppname: dialogForm.suppname,
    suppgrade: dialogForm.suppgrade,
    supppeople: dialogForm.supppeople,
    phone: dialogForm.phone,
    status: dialogForm.status,
    desc: dialogForm.desc
  }
  const { data } = await https.Writes.put("/Supplier/UpdateSupplier", payload)
  return data
}

const handleSubmit = () => {
  dialogFormRef.value?.validate(async valid => {
    if (!valid) return
    saving.value = true
    try {
      const result =
        dialogMode.value === 'create' ? await submitAdd() : await submitUpdate()
      if (getStatusCode(result) === 1) {
        ElMessage.success(getPayloadMsg(result) || '操作成功')
        dialogVisible.value = false
        fetchSuppliers()
        if (dialogMode.value === 'create') {
          fetchSupplierGrades()
        }
      } else {
        ElMessage.error(getPayloadMsg(result) || '操作失败')
      }
    } catch (error: any) {
      console.error('handleSubmit error', error)
      ElMessage.error(error?.message || '保存失败，请稍后重试')
    } finally {
      saving.value = false
    }
  })
}

const handleBatchDelete = async () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择需要删除的供应商')
    return
  }
  try {
    await ElMessageBox.confirm(
      `确定删除选中的 ${selectedIds.value.length} 条供应商数据吗？`,
      '提示',
      { type: 'warning' }
    )
    const { data } = await https.Writes.delete("/Supplier/DelAllSupplier", {
      data: { ids: selectedIds.value }
    })
    if (getStatusCode(data) === 1) {
      ElMessage.success(getPayloadMsg(data) || '删除成功')
      fetchSuppliers()
    } else {
      ElMessage.error(getPayloadMsg(data) || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('handleBatchDelete error', error)
      ElMessage.error(error?.message || '删除失败，请稍后重试')
    }
  }
}

onMounted(() => {
  fetchSuppliers()
  fetchSupplierGrades()
})
</script>

<style scoped>
.supplier-list-page {
  padding: 16px;
  background: #f5f7fa;
}

.filter-card {
  margin-bottom: 12px;
}

.table-toolbar {
  display: flex;
  justify-content: flex-start;
  gap: 12px;
  margin-bottom: 12px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
</style>

